package
{
	import aleksic.videogrid.Grid;
	import aleksic.videogrid.Player;
	
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.external.ExternalInterface;
	
	public class VideoGrid extends Sprite
	{
		
		public var vars:VideoGridFlashVars;
		
		/**
		 * The video grid instance
		 * @see aleksic.video.Grid;
		 */
		public var grid:Grid;
		
		public function VideoGrid()
		{
			ExternalInterface.addCallback('unload', unload);
			ExternalInterface.addCallback('togglePlayback', toggleGridPlayback);
			ExternalInterface.addCallback('playVideo', gridPlay);
			ExternalInterface.addCallback('pauseVideo', gridPause);
			vars = new VideoGridFlashVars(loaderInfo.parameters);
			addEventListener(Event.ADDED_TO_STAGE, handleAdded);
		}
		
		
		private function toggleGridPlayback(... args):void
		{
			if (!grid) {
				return;
			}
			if (!args || !args.length) {
				grid.togglePlayback();
			}
			else {
				for each (var i:int in args) {
					var player:Player = grid.getChildAt(i) as Player;
					if (player) {
						player.toggle();
					}
				}
			}
		}
		
		private function gridPause(... args):void
		{
			if (!grid) {
				return;
			}
			if (!args || !args.length) {
				grid.pause();
			}
			else {
				for each (var i:int in args) {
					var player:Player = grid.getChildAt(i) as Player;
					if (player) {
						player.pause();
					}
				}
			}
		}
		
		private function gridPlay(... args):void
		{
			if (!grid) {
				return;
			}
			if (!args || !args.length) {
				grid.play();
			}
			else {
				for each (var i:int in args) {
					var player:Player = grid.getChildAt(i) as Player;
					if (player) {
						player.play();
					}
				}
			}
		}
		
		protected function handleAdded(event:Event):void
		{
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			createGrid();
		}
		
		private function createGrid():void
		{
			grid = new Grid(vars);
			grid.x = vars.gridOffsetX;
			grid.y = vars.gridOffsetY;
			addChild(grid);
			if (vars.gridAutoCenter) {
				centerGrid();
				stage.addEventListener(Event.RESIZE, centerGrid);
			}
		}		
		
		private function centerGrid(e:Event=null):void
		{
			if (grid) {
				grid.x = 0.5 * (stage.stageWidth - grid.width) + vars.gridOffsetX;
				grid.y = 0.5 * (stage.stageHeight - grid.height) + vars.gridOffsetY;
			}
		}
		
		private function unload():void
		{
			grid.unload();
		}
		 
		
		
	}
}